import { NextResponse } from 'next/server'
import { checkLanguage } from '@/lib/middleware-helper'

function middleware(request) {
  const { pathname } = request.nextUrl

  console.log('Middleware triggered:', {
    fullUrl: request.url,
    pathname: pathname,
    basePath: request.nextUrl.basePath
  })

  // 处理语言重定向（仅在非API路由上）
  if (!pathname.startsWith('/api')) {
    const response = checkLanguage(request)
    if (response) {
      return response
    }
  }

  // 定义公开路径（考虑多语言）
  const publicPaths = ['/login', '/api/auth','/api/wepay', '/zh/login', '/en/login','/yyds-qrcode','/zy/yyds-qrcode','/en/yyds-qrcode']
  const isPublicPath = publicPaths.some(path => pathname.startsWith(path))

  // 检查认证状态
  const isAuth = request.cookies.has('next-auth.session-token') ||
                request.cookies.has('__Secure-next-auth.session-token')

  // 如果是登录页面，且已登录，重定向到之前的页面或首页
  if ((pathname.includes('/login')) && isAuth) {
    const callbackUrl = request.nextUrl.searchParams.get('callbackUrl')
    if (callbackUrl && !callbackUrl.includes('/login')) {
      return NextResponse.redirect(new URL(callbackUrl, request.url))
    }
    // 如果没有回调URL，重定向到首页
    const lang = pathname.startsWith('/zh') ? '/zh' :
                pathname.startsWith('/en') ? '/en' : '/zh'
    return NextResponse.redirect(new URL(`/ty${lang}/reservation`, request.url))
  }

  // 如果不是公开路径且未登录，重定向到登录页
  if (!isPublicPath && !isAuth) {
    // 保持相同的语言路径
    const lang = pathname.startsWith('/zh') ? '/zh' :
                pathname.startsWith('/en') ? '/en' : '/zh'
    const url = new URL(`/ty${lang}/login`, request.url)
    url.searchParams.set('callbackUrl', `${process.env.NEXTAUTH_URL}/ty${pathname}`)
    return NextResponse.redirect(url)
  }

  return NextResponse.next()
}

export default middleware

export const config = {
  matcher: [
    // 添加对根路径的匹配
    '/',
    '/ty',
    '/ty/',
    /*
     * 匹配所有路径，除了:
     * - _next (Next.js internals)
     * - 静态文件
     */
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ]
}
